package com.gohi.main.util;

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.image.BufferedImage;

import java.io.IOException;

import java.util.Random;

import javax.imageio.ImageIO;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

/**
 * 验证码生成 
 * 
 * */
public class VerifyCodeServlet extends HttpServlet {

	private static final long serialVersionUID = -8992901834461098987L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)

	throws ServletException, IOException {

		this.doPost(request, response);

	}
	
	/* * 绘制干扰线 */
	private void drowLine(Random random,Graphics g,int width,int height) {
		int x = random.nextInt(width);
		int y = random.nextInt(height);
		int xl = random.nextInt(13);
		int yl = random.nextInt(15);
		g.drawLine(x, y, x + xl, y + yl);
	}

	/**
	 * 生成数字和字母的验证码
	 * 
	 * @author gmaishgdx
	 * */
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)

	throws ServletException, IOException {
		
		int lineSize = 40;	//绘制干扰线数量
		String number = "4";	//验证码位数默认
        try {
			number = Utils.getBundelPath("config", "verifyNumber");
		} catch (Exception e) {
			e.printStackTrace();
		}
		int num = Integer.valueOf(number); //位数
		int width = 18 * num;
		int height = 25;

		BufferedImage img = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);

		// 得到该图片的绘图对象
		Graphics g = img.getGraphics();

		Random r = new Random();

		Color c = new Color(255, 255, 255);

		g.setColor(c);

		// 填充整个图片的颜色

		g.fillRect(0, 0, width, height);

		// 向图片中输出数字和字母

		StringBuffer sb = new StringBuffer();

		char[] ch = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ".toCharArray();

		int index, len = ch.length;
		
		for (int i = 0; i < num; i++) {

			index = r.nextInt(len);
			 
			g.setColor(new Color(r.nextInt(101),r.nextInt(111),r.nextInt(121)));//随机颜色

			g.setFont(new Font("Arial", Font.CENTER_BASELINE | Font.ITALIC, 20));// 输出的字体和大小
			
			g.translate(r.nextInt(3), r.nextInt(3));
			

			g.drawString("" + ch[index], (i * 15) + 3, 18);// 写什么数字，在图片的什么位置画

			sb.append(ch[index]);

		}
		
		for (int i = 0; i < lineSize; i++) {
			drowLine(r, g, width, height);
		}

		request.getSession().setAttribute("imgVerifyCode", sb.toString());

		ImageIO.write(img, "JPEG", response.getOutputStream());

	}

}